<template>
  <div class="demand-review">
    
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="需求标题">
          <el-input v-model="searchForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        <el-form-item label="发布企业">
          <el-input v-model="searchForm.company" placeholder="请输入发布企业" />
        </el-form-item>
        <el-form-item label="需求类型">
          <el-select v-model="searchForm.type" placeholder="请选择需求类型">
            <el-option label="全部" value="" />
            <el-option label="贸易" value="trade" />
            <el-option label="人才" value="talent" />
          </el-select>
        </el-form-item>
        <el-form-item label="需求状态">
          <el-select v-model="searchForm.status" placeholder="请选择需求状态" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending_review" />
            <el-option label="在线" value="online" />
            <el-option label="已关闭" value="closed" />
            <el-option label="驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>需求内容列表</span>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="需求标题" min-width="25%">
          <template #default="scope">
            <el-button link @click="handleViewDetail(scope.row)">
              {{ scope.row.title }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="company" label="发布企业" min-width="20%" />
        <el-table-column prop="publishTime" label="发布时间" min-width="20%" />
        <el-table-column prop="type" label="需求类型" min-width="15%">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="15%">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="30%">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleApprove(scope.row)">
              通过上线
            </el-button>
            <el-button type="danger" size="small" @click="handleReject(scope.row)">
              驳回
            </el-button>
            <el-button type="warning" size="small" @click="handleSetPending(scope.row)">
              改为待审核
            </el-button>
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="需求详情"
      width="70%"
    >
      <div v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="需求标题">{{ currentDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="发布企业">{{ currentDetail.company }}</el-descriptions-item>
          <el-descriptions-item label="需求类型">{{ getTypeText(currentDetail.type) }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ currentDetail.publishTime }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ currentDetail.location || '未指定' }}</el-descriptions-item>
          <el-descriptions-item label="薪资范围">{{ currentDetail.budget || '未指定' }}</el-descriptions-item>
          <el-descriptions-item label="合作方式">{{ currentDetail.cooperation || '未指定' }}</el-descriptions-item>
          <el-descriptions-item label="有效期至">{{ currentDetail.validityPeriod || '未指定' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>需求描述</h4>
          <div v-html="currentDetail.description || '暂无描述'"></div>
        </div>
        
        <div class="detail-section">
          <h4>具体要求</h4>
          <div v-html="currentDetail.requirements || '暂无要求'"></div>
        </div>
        
        <div class="detail-section" v-if="currentDetail.targetNationalities">
          <h4>目标国籍</h4>
          <p>{{ currentDetail.targetNationalities }}</p>
        </div>
        
        <div class="detail-section" v-if="currentDetail.languageRequirements">
          <h4>语言要求</h4>
          <p>{{ currentDetail.languageRequirements }}</p>
        </div>
        
        <div class="detail-section" v-if="currentDetail.majorRequirements">
          <h4>专业要求</h4>
          <p>{{ currentDetail.majorRequirements }}</p>
        </div>
        
        <div class="detail-section" v-if="currentDetail.degreeRequirements">
          <h4>学历要求</h4>
          <p>{{ currentDetail.degreeRequirements }}</p>
        </div>
        
        <div class="detail-section" v-if="currentDetail.experienceRequirements">
          <h4>经验要求</h4>
          <p>{{ currentDetail.experienceRequirements }}</p>
        </div>
        
        <div class="detail-section" v-if="currentDetail.benefits">
          <h4>福利待遇</h4>
          <div v-html="currentDetail.benefits"></div>
        </div>
        
        <div class="detail-section" v-if="currentDetail.companyAdvantages">
          <h4>公司优势</h4>
          <div v-html="currentDetail.companyAdvantages"></div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 驳回对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="驳回需求"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="驳回理由" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmReject">确认驳回</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDemandList, getDemandListByStatus, getDemandDetail, approveDemand, rejectDemand, setDemandPending } from '@/api/demandReview'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const currentDetail = ref(null)

const searchForm = reactive({
  title: '',
  company: '',
  type: '',
  status: '',
  dateRange: []
})

const rejectForm = reactive({
  reason: ''
})

const tableData = ref([])

// 获取需求列表数据
const fetchDemandList = async () => {
  loading.value = true
  try {
    let response
    if (searchForm.status) {
      // 如果选择了状态，使用按状态筛选的接口
      response = await getDemandListByStatus(searchForm.status)
    } else {
      // 否则使用获取全部列表的接口
      response = await getDemandList()
    }
    
    if (response.code === 200) {
      tableData.value = response.data.demands.map(demand => ({
        id: demand.demandId,
        title: demand.title,
        company: demand.enterpriseName,
        publishTime: demand.publishTime,
        type: demand.demandType,
        status: demand.demandStatus,
        contact: demand.contact || '',
        phone: demand.phone || '',
        email: demand.email || '',
        budget: demand.salaryRange || '',
        description: demand.description || '',
        requirements: demand.requirements || '',
        cooperation: demand.cooperationMode || ''
      }))
      total.value = response.data.totalCount
    } else {
      ElMessage.error(response.message || '获取需求列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取需求列表失败')
  } finally {
    loading.value = false
  }
}

const getTypeTag = (type) => {
  const typeMap = {
    trade: 'success',
    talent: 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    trade: '贸易',
    talent: '人才'
  }
  return typeMap[type] || '未知'
}

const getStatusType = (status) => {
  const statusMap = {
    draft: 'info',
    pending_review: 'warning',
    online: 'success',
    closed: 'info',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    pending_review: '待审核',
    online: '在线',
    closed: '已关闭',
    rejected: '驳回'
  }
  return statusMap[status] || '未知'
}

const handleSearch = () => {
  // 实现搜索逻辑
  console.log('搜索条件:', searchForm)
  fetchDemandList()
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.company = ''
  searchForm.type = ''
  searchForm.status = ''
  searchForm.dateRange = []
  fetchDemandList()
}

const handleRefresh = () => {
  // 实现刷新逻辑
  console.log('刷新数据')
  fetchDemandList()
}

const handleViewDetail = async (row) => {
  try {
    const response = await getDemandDetail(row.id)
    if (response.code === 200) {
      const detail = response.data
      currentDetail.value = {
        id: detail.demandId,
        title: detail.title,
        company: detail.enterpriseName,
        publishTime: detail.publishTime,
        type: detail.demandType,
        status: detail.demandStatus,
        contact: detail.contact || '',
        phone: detail.phone || '',
        email: detail.email || '',
        budget: detail.salaryRange || '',
        description: detail.description || '',
        requirements: detail.requirements || '',
        cooperation: detail.cooperationMode || '',
        targetNationalities: detail.targetNationalities || '',
        languageRequirements: detail.languageRequirements || '',
        majorRequirements: detail.majorRequirements || '',
        degreeRequirements: detail.degreeRequirements || '',
        experienceRequirements: detail.experienceRequirements || '',
        location: detail.location || '',
        validityPeriod: detail.validityPeriod || '',
        benefits: detail.benefits || '',
        companyAdvantages: detail.companyAdvantages || ''
      }
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取需求详情失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取需求详情失败')
  }
}

const handleApprove = (row) => {
  ElMessageBox.confirm(
    '确定要通过该需求并上线吗？',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await approveDemand(row.id)
      if (response.code === 200) {
        ElMessage.success(response.message || '需求已通过并上线')
        // 刷新列表数据
        fetchDemandList()
      } else {
        ElMessage.error(response.message || '审核操作失败')
      }
    } catch (error) {
      ElMessage.error(error.message || '审核操作失败')
    }
  })
}

const handleReject = (row) => {
  currentDetail.value = row
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

const handleConfirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入驳回理由')
    return
  }
  
  try {
    const response = await rejectDemand(currentDetail.value.id, rejectForm.reason)
    if (response.code === 200) {
      ElMessage.success(response.message || '需求已驳回')
      rejectDialogVisible.value = false
      // 刷新列表数据
      fetchDemandList()
    } else {
      ElMessage.error(response.message || '驳回操作失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '驳回操作失败')
  }
}

// 将需求改为待审核
const handleSetPending = (row) => {
  ElMessageBox.confirm(
    '确定要将该需求状态改为待审核吗？',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await setDemandPending(row.id)
      if (response.code === 200) {
        ElMessage.success(response.message || '需求状态已修改为待审核')
        // 刷新列表数据
        fetchDemandList()
      } else {
        ElMessage.error(response.message || '状态修改失败')
      }
    } catch (error) {
      ElMessage.error(error.message || '状态修改失败')
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

onMounted(() => {
  // 初始化数据
  fetchDemandList()
})
</script>

<style scoped>
.demand-review {
  padding: 20px;
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: #f5f5f5;
}

.demand-review h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100% !important;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  padding: 0 12px;
}

/* 表格列宽度优化 */
:deep(.el-table .el-table__column) {
  min-width: 120px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  font-weight: 600;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

/* 移除按钮和弹窗的黑色边框 */
:deep(.el-button:focus) {
  outline: none !important;
  border-color: transparent !important;
}

:deep(.el-button:focus-visible) {
  outline: none !important;
  border-color: transparent !important;
}

:deep(.el-dialog__headerbtn:focus) {
  outline: none !important;
}

:deep(.el-dialog__headerbtn:focus-visible) {
  outline: none !important;
}

:deep(.el-input:focus-within) {
  outline: none !important;
}

:deep(.el-select:focus-within) {
  outline: none !important;
}

:deep(.el-textarea:focus-within) {
  outline: none !important;
}

:deep(.el-date-editor:focus-within) {
  outline: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .demand-review {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style> 